package io;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.Set;

public class SocketNIOTest {

    public static void main(String[] args) {
        new Server().start();
    }

    static class Server extends Thread {
        @Override
        public void run() {
            try (Selector selector = Selector.open();
                 ServerSocketChannel serverSocket = ServerSocketChannel.open();) {// 创建Selector和Channel
                serverSocket.bind(new InetSocketAddress(InetAddress.getLocalHost(), 8989));
                serverSocket.configureBlocking(false);
                // 注册到Selector，并说明关注点
                serverSocket.register(selector, SelectionKey.OP_ACCEPT);
                while (true) {
                    System.out.println("select");
                    selector.select();// 阻塞等待就绪的Channel，这是关键点之一
                    System.out.println("selected");

                    Set<SelectionKey> selectedKeys = selector.selectedKeys();
                    Iterator<SelectionKey> iter = selectedKeys.iterator();
                    while (iter.hasNext()) {
                        SelectionKey key = iter.next();
                        System.out.println(key);
                        // 生产系统中一般会额外进行就绪状态检查
                        countdown((ServerSocketChannel) key.channel());
                        iter.remove();
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        private void countdown(ServerSocketChannel server) throws IOException {
            try (SocketChannel client = server.accept();) {
                client.write(Charset.defaultCharset().encode("-- hello!\n"));
                client.write(Charset.defaultCharset().encode("-- start countdown\n"));
                for (int i = 0; i < 10; i++) {
                    client.write(Charset.defaultCharset().encode(String.valueOf(10 - i)+ "\n"));
                    try {
                        sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}
